/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.worker.controller;

import org.ourgrid.common.interfaces.control.WorkerControl;
import org.ourgrid.common.interfaces.to.WorkerStatus;
import org.ourgrid.worker.WorkerConstants;
import org.ourgrid.worker.dao.WorkerStatusDAO;
import org.ourgrid.worker.receiver.IdlenessDetectorWorkerControlClient;

import br.edu.ufcg.lsd.commune.Application;
import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;

/**
 * @author alan
 *
 */
public class IdlenessDetectorController {

	private static IdlenessDetectorController instance = null;
	
	public static synchronized IdlenessDetectorController getInstance() {
		if (instance == null) {
			instance = new IdlenessDetectorController();
		}
		return instance;
	}

	public void pauseWorker(ServiceManager serviceManager) {
		WorkerStatus actualStatus = serviceManager.getDAO(WorkerStatusDAO.class).getStatus();
		if(!actualStatus.equals(WorkerStatus.OWNER)) {
			WorkerControl workerControl = getWorkerControl(serviceManager);
			IdlenessDetectorWorkerControlClient dummyWorkerControlClient = getWorkerControlClient(serviceManager);
			workerControl.pause(dummyWorkerControlClient);
		}
	}

	private WorkerControl getWorkerControl(ServiceManager serviceManager) {
		return (WorkerControl) serviceManager.getObjectDeployment(
				Application.CONTROL_OBJECT_NAME).getObject();
	}

	private IdlenessDetectorWorkerControlClient getWorkerControlClient(
			ServiceManager serviceManager) {
		return (IdlenessDetectorWorkerControlClient) serviceManager.getObjectDeployment(WorkerConstants.IDLENESS_DETECTOR_WORKER_CONTROL_CLIENT).getObject();
	}
	
	public void resumeWorker(ServiceManager serviceManager) {
		WorkerStatus actualStatus = serviceManager.getDAO(WorkerStatusDAO.class).getStatus();
		if(actualStatus.equals(WorkerStatus.OWNER)) {
			WorkerControl workerControl = getWorkerControl(serviceManager);
			IdlenessDetectorWorkerControlClient dummyWorkerControlClient = getWorkerControlClient(serviceManager);
			workerControl.resume(dummyWorkerControlClient);
		}
	}

}
